import type { ComputedRef, Ref } from 'vue';
import type { AdListProps } from '../types/adList';
import { unref, computed, nextTick, watchEffect } from 'vue';
import { useEventListener } from '@/hooks/event/useEventListener';

export function useListFooter(
  propsRef: ComputedRef<AdListProps>,
  listElRef: Ref<ComponentRef>,
  getDataSourceRef: Ref<Recordable[]>,
  scrollRef?: ComputedRef<{
    x: string | number | true;
    y: string | number | null;
    scrollToFirstRowOnChange: boolean;
  }>,
) {
  const getIsEmptyData = computed(() => {
    return (unref(getDataSourceRef) || []).length === 0;
  });

  const getFooterProps = computed((): Recordable => {
    const { summaryFunc, showSummary, summaryData } = unref(propsRef);
    const hideFooter = !showSummary && !unref(getIsEmptyData);
    return {
      hideFooter,
      summaryFunc,
      summaryData,
      scroll: unref(scrollRef),
    };
  });

  watchEffect(() => {
    handleSummary();
  });

  function handleSummary() {
    const { showSummary } = unref(propsRef);
    if (!showSummary || unref(getIsEmptyData)) return;

    nextTick(() => {
      const listEl = unref(listElRef);
      if (!listEl) return;
      const bodyDom = listEl.$el.querySelector('.ant-list-items');
      useEventListener({
        el: bodyDom,
        name: 'scroll',
        listener: () => {
          const footerBodyDom = listEl.$el.querySelector('.ant-list-footer') as HTMLDivElement;
          if (!footerBodyDom || !bodyDom) return;
          footerBodyDom.scrollLeft = bodyDom.scrollLeft;
        },
        wait: 0,
        options: true,
      });
    });
  }
  return { getFooterProps };
}
